package com.hmy.contract.service.contract.save.feign;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmy.ccp.common.dto.ContextUserInfo;
import com.hmy.ccp.error.exception.HMYRuntimeException;
import com.hmy.ccp.starter.web.utils.UserContextUtil;
import com.hmy.contract.common.constant.ContractConstants;
import com.hmy.contract.common.constant.RedisKeyConstants;
import com.hmy.contract.common.properties.LessorInfoProperties;
import com.hmy.contract.common.utils.CommonCodeGenerator;
import com.hmy.contract.commons.enums.ContractStatusEnum;
import com.hmy.contract.dal.mapper.ContractMapper;
import com.hmy.contract.dal.po.ContractConfigPo;
import com.hmy.contract.dal.po.ContractPo;
import com.hmy.contract.service.contract.IContractConfigService;
import com.hmy.contract.service.contract.save.ISaveContractBaseService;
import com.hmy.contract.service.dto.contract.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author seven.qi 齐胜南
 * @version 1.0
 * @description
 * @date 2024/3/11 15:33
 */
@Service
public class FeignSaveElectronicContractService implements ISaveContractBaseService<SaveContractDto, ContractPo> {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ContractMapper contractMapper;

    @Resource
    private LessorInfoProperties lessorInfoProperties;

    @Resource
    private IContractConfigService contractConfigService;

    @Override
    public void beforeCreate(SaveContractDto dto) {
        validateData(dto);
    }

    @Override
    public ContractPo save(SaveContractDto dto) {
        String contractNo = generateContractNo(dto);
        if (CollUtil.isNotEmpty(dto.getFieldMap())) {
            dto.getFieldMap().put("合同编号", contractNo);
        }
        ContractPo contractPo = convertPo(dto);
        contractPo.setContractNo(contractNo);
        contractMapper.insert(contractPo);
        return contractPo;
    }

    @Override
    public void afterCreate(SaveContractDto dto) {

    }

    private String generateContractNo(SaveContractDto dto) {
        return CommonCodeGenerator.getNextCode(redisTemplate, ContractConstants.ELECTRONIC_CONTRACT_PREFIX, RedisKeyConstants.CONTRACT_CODE_QUEUE);
    }

    private void validateData(SaveContractDto dto) {
        if (CollUtil.isEmpty(dto.getContractActorList())) {
            throw new HMYRuntimeException(502000018);
        }
        if (StrUtil.isEmpty(dto.getRelationNo())) {
            throw new HMYRuntimeException(502000019);
        }
        if (dto.getRelationId() == null) {
            throw new HMYRuntimeException(502000020);
        }
//        if (CollUtil.isEmpty(dto.getFieldMap())) {
//            throw new HMYRuntimeException(502000021);
//        }
        if (dto.getBusinessType() == null) {
            throw new HMYRuntimeException(502000022);
        }
        if (dto.getType() == null) {
            throw new HMYRuntimeException(502000023);
        }
        LambdaQueryWrapper<ContractConfigPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ContractConfigPo::getContractBusinessType, dto.getBusinessType());
        wrapper.eq(ContractConfigPo::getIsDeleted, Boolean.FALSE);
        ContractConfigPo contractConfigRo = contractConfigService.getOne(wrapper);
        if (ObjectUtil.isEmpty(contractConfigRo)) {
            throw new HMYRuntimeException(502000017);
        }
        ActorDetailExtensionDto bean = JSONUtil.toBean(contractConfigRo.getActorConfig(), ActorDetailExtensionDto.class);
        if (bean.getActorDetailList().size() != dto.getContractActorList().size()) {
            throw new HMYRuntimeException(502000024);
        }
//        List<String> templateFiledList = JSONUtil.toList(contractConfigRo.getTemplateFieldConfig(), String.class);
//        Map<String, Object> fieldMap = createContractRequest.getFieldMap();
//        fieldMap.keySet().forEach(key -> {
//            if (templateFiledList.stream().noneMatch(str -> str.contains(key))) {
//                throw new HMYRuntimeException(502000025);
//            }
//        });


    }


    private ContractPo convertPo(SaveContractDto dto) {
        ContractBusinessInfoDto businessInfo = dto.getContractBusinessInfo();
        ContractCustomerInfoDto contractCustomerInfo = businessInfo.getContractCustomerInfo();

        ContractPo contractPo = new ContractPo();
        contractPo.setContractName(businessInfo.getTaskSubject());
        contractPo.setContractType(dto.getType());
        contractPo.setContractFileName(businessInfo.getTaskSubject());
        contractPo.setLessorInfo(JSONUtil.toJsonStr(lessorInfoProperties));
        contractPo.setLessorName(lessorInfoProperties.getName());

        if (ObjectUtil.isNotEmpty(businessInfo.getOrderId())) {
            contractPo.setOrderId(businessInfo.getOrderId());
        } else {
            contractPo.setOrderId(-1L);
        }
        if (StrUtil.isNotEmpty(businessInfo.getOrderNo())) {
            contractPo.setOrderNo(businessInfo.getOrderNo());
        } else {
            contractPo.setOrderNo("");
        }
        if (ObjectUtil.isNotEmpty(contractCustomerInfo)) {
            contractPo.setCustomerName(contractCustomerInfo.getCustomerName());
            contractPo.setCustomerPhone(contractCustomerInfo.getCustomerPhone());
            contractPo.setCustomerIdCardNo(contractCustomerInfo.getCustomerIdCardNo());
        }
        if (CollUtil.isNotEmpty(businessInfo.getContractAuthorizerList())) {
            contractPo.setAuthorizerInfo(JSONUtil.toJsonStr(businessInfo.getContractAuthorizerList()));
        }
        contractPo.setBusinessType(dto.getBusinessType());
        contractPo.setRelationId(dto.getRelationId());
        contractPo.setRelationNo(dto.getRelationNo());
        contractPo.setStatus(ContractStatusEnum.WAITING_CREATE.getStatus());
        if (CollUtil.isNotEmpty(dto.getFieldMap())) {
            TemplateDataDetailExtensionDto templateDataDetailExtensionDto = new TemplateDataDetailExtensionDto();
            templateDataDetailExtensionDto.setFields(dto.getFieldMap());
            contractPo.setTemplateDataDetailExtension(JSONUtil.toJsonStr(templateDataDetailExtensionDto));
        }
        ActorDetailExtensionDto actorDetailExtensionDto = new ActorDetailExtensionDto();
        actorDetailExtensionDto.setActorDetailList(dto.getContractActorList());
        contractPo.setActorDetailExtension(JSONUtil.toJsonStr(actorDetailExtensionDto));

        contractPo.setContractFileUrl(dto.getContractFileUrl());
        contractPo.setContractFileModel(dto.getContractFileModel());

        ContextUserInfo currentUser = UserContextUtil.getCurrentUser();
        contractPo.setSaleManagerId(businessInfo.getSaleManagerId());
        contractPo.setSaleManagerName(businessInfo.getSaleManagerName());
        if (null != businessInfo.getSaleManagerDepartId()) {
            contractPo.setDeptId(businessInfo.getSaleManagerDepartId());
        }
        contractPo.setCreatorId(currentUser.getId());
        contractPo.setCreatorName(currentUser.getUserName());
        contractPo.setUpdaterId(currentUser.getId());
        contractPo.setUpdaterName(currentUser.getUserName());
        return contractPo;
    }

}
